package pub.cleangao.memm.transport.netty.codec;


import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;
import pub.cleangao.memm.transport.TransportConst;
import pub.cleangao.memm.transport.netty.compress.Compress;
import pub.cleangao.memm.transport.netty.compress.CompressSupplier;
import pub.cleangao.memm.transport.netty.compress.CompressType;
import pub.cleangao.memm.transport.message.MessageType;
import pub.cleangao.memm.transport.message.RpcMessage;
import pub.cleangao.memm.transport.netty.serialize.SerializationType;
import pub.cleangao.memm.transport.netty.serialize.Serializer;
import pub.cleangao.memm.transport.netty.serialize.SerializerSupplier;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * protocol:
 * <p>
 * 0     1     2     3     4        5     6     7     8         9          10      11     12  13  14   15 16
 * +-----+-----+-----+-----+--------+----+----+----+------+-----------+-------+----- --+-----+-----+---+---+
 * |   magic   code        |version | full length         |messageType| codec |compress|    RequestId      |
 * +-----------------------+--------+---------------------+-----------+-------+--------+-------------------+
 * |                                                                                                       |
 * |                                         body                                                          |
 * |                                                                                                       |
 * |                                        ... ...                                                        |
 * +-------------------------------------------------------------------------------------------------------+
 * 4B  magic code（魔法数）   1B version（版本）   4B full length（消息长度）    1B messageType（消息类型）
 * 1B compress（压缩类型） 1B codec（序列化类型）    4B  requestId（请求的Id）
 * body（object类型数据）
 *
 * @author clean.gao
 */
@Slf4j
public class MessageEncoder extends MessageToByteEncoder<RpcMessage> {


    private static final AtomicInteger ATOMIC_INTEGER = new AtomicInteger(0);

    @Override
    protected void encode(ChannelHandlerContext ctx, RpcMessage rpcMessage, ByteBuf out) throws Exception {
        try {
            out.writeBytes(TransportConst.MAGIC_NUMBER);
            out.writeByte(TransportConst.VERSION);
            // leave a place to write the value of full length
            out.writerIndex(out.writerIndex() + 4);
            byte messageType = rpcMessage.getMessageType();
            out.writeByte(messageType);
            out.writeByte(rpcMessage.getCodec());
            out.writeByte(CompressType.NONE.getCode());
            out.writeInt(ATOMIC_INTEGER.getAndIncrement());
            // build full length
            byte[] bodyBytes = null;
            int fullLength = TransportConst.PROTOCOL_HEAD_LENGTH;
            // if messageType is not heartbeat message,fullLength = head length + body length
            if (messageType != MessageType.HEARTBEAT_REQUEST.value()
                    && messageType != MessageType.HEARTBEAT_RESPONSE.value()) {
                // serialize the object
                String codecName = SerializationType.getName(rpcMessage.getCodec());
                Serializer serializer = SerializerSupplier.getByType(codecName);
                bodyBytes = serializer.serialize(rpcMessage.getData());
                // compress the bytes
                String compressName = CompressType.getName(rpcMessage.getCompress());
                if (compressName != null) {
                    Compress compress = CompressSupplier.getByType(compressName);
                    if (compress != null) {
                        bodyBytes = compress.compress(bodyBytes);
                    }
                }
                fullLength += bodyBytes.length;
            }

            if (bodyBytes != null) {
                out.writeBytes(bodyBytes);
            }
            int writeIndex = out.writerIndex();
            out.writerIndex(writeIndex - fullLength + TransportConst.MAGIC_NUMBER.length + 1);
            out.writeInt(fullLength);
            out.writerIndex(writeIndex);
        } catch (Exception e) {
            log.error("encode request error: {}", e.getMessage());
        }

    }
}
